package com.changyinBus.web.controller.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.changyinBus.common.utils.StringUtils;
import com.changyinBus.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeChatJsApiService {
    @Value("${wechat.open.appId}")
    private String appId;
    @Value("${wechat.open.appSecret}")
    private String appSecret;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 获取JS-SDK配置
     */
    public Map<String, String> getJsApiConfig(String url) throws Exception {
        String accessToken = getAccessToken();
        String jsapiTicket = getJsapiTicket(accessToken);

        // 生成配置参数
        String nonceStr = generateNonceStr();
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        // 生成签名
        String signature = generateSignature(jsapiTicket, nonceStr, timestamp, url);

        Map<String, String> config = new HashMap<>();
        config.put("appId", appId);
        config.put("timestamp", timestamp);
        config.put("nonceStr", nonceStr);
        config.put("signature", signature);

        return config;
    }

    /**
     * 生成签名
     */
    private String generateSignature(String jsapiTicket, String nonceStr,
                                     String timestamp, String url) {
        try {
            String string1 = "jsapi_ticket=" + jsapiTicket +
                    "&noncestr=" + nonceStr +
                    "&timestamp=" + timestamp +
                    "&url=" + url;

            //log.info("签名原始字符串: {}", string1);
            String signature = DigestUtils.sha1Hex(string1);
            //log.info("生成的签名: {}", signature);
            return signature;
        } catch (Exception e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }

    /**
     * 获取Access Token
     */
    public String getAccessToken() throws Exception {
        String cacheKey = "wechat:access_token";
        String cachedToken = (String)redisTemplate.opsForValue().get(cacheKey);

        if (StringUtils.hasText(cachedToken)) {
            return cachedToken;
        }

        String url = String.format(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                appId, appSecret
        );

        String response = HttpUtil.get(url);
        JSONObject json = JSONUtil.parseObj(response);

        if (json.containsKey("access_token")) {
            String accessToken = json.getStr("access_token");
            int expiresIn = json.getInt("expires_in", 7200) - 300; // 提前5分钟过期

            // 缓存access_token
            redisTemplate.opsForValue().set(
                    cacheKey, accessToken, Duration.ofSeconds(expiresIn)
            );

            return accessToken;
        } else {
            throw new RuntimeException("获取access_token失败: " + json.getStr("errmsg"));
        }
    }

    /**
     * 获取JSAPI Ticket
     */
    private String getJsapiTicket(String accessToken) throws Exception {
        String cacheKey = "wechat:jsapi_ticket";
        String cachedTicket =  (String)redisTemplate.opsForValue().get(cacheKey);

        if (StringUtils.hasText(cachedTicket)) {
            return cachedTicket;
        }

        String url = String.format(
                "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",
                accessToken
        );

        String response = HttpUtil.get(url);
        JSONObject json = JSONUtil.parseObj(response);

        if (json.getInt("errcode") == 0) {
            String jsapiTicket = json.getStr("ticket");
            int expiresIn = json.getInt("expires_in", 7200) - 300; // 提前5分钟过期

            // 缓存jsapi_ticket
            redisTemplate.opsForValue().set(
                    cacheKey, jsapiTicket, Duration.ofSeconds(expiresIn)
            );

            return jsapiTicket;
        } else {
            throw new RuntimeException("获取jsapi_ticket失败: " + json.getStr("errmsg"));
        }
    }

    /**
     * 生成随机字符串
     */
    private String generateNonceStr() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
}
